package com.yzh.springboot_rbac.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class TreeMany {
    /*此类用于构建多个根节点的树结构*/
    public static List<TreeNode> buildTree(List<TreeNode> treeNodes) {
        /*第一个for循环，把所有节点放到map集合里*/
        HashMap<Integer, TreeNode> treeMap = new HashMap<>();
        for (TreeNode node: treeNodes) {
            treeMap.put(node.getId(), node);
        }

        List<TreeNode> rootList = new ArrayList<>();
        /*第二个for循环，判断根节点，构建树结构*/
        for (TreeNode node: treeNodes) {
            if (node.getParent_id() == 0) {
                rootList.add(node);
            } else {
                TreeNode parentNode = treeMap.get(node.getParent_id());
                if (parentNode != null) {
                    if (parentNode.getChildren() == null) {
                        parentNode.setChildren(new ArrayList<>());
                    }
                    parentNode.getChildren().add(node);
                }
            }
        }
        return rootList;
    }
}
